// firstPackage/pages/msgModule/chatRoom/chatRoom.js
import GraphemeSplitter from "../../../../sdk/graphemeSplitter/index"
import debounce from "../../../../tools/debounce"
// const TIM = require("../../../../sdk/tim-wx-sdk/index")
let app = getApp();
//不是房源进来的情况，绝对高度
const COMMON_SCROLLBOTTOM = 120;

//工具弹窗高度(包含输入框)
const FUNCTION_TOOLHEIGHT = 420;
//表情弹窗高度(包含输入框)
const EMOJI_TOOLHEIGHT = 620;


import { sendImMsgConfig } from "../../../../service/config"
// imTODO
import { queryIMMessageList, setMessageIsRead } from '../../../../service/newIm_service'
import { NEWIMAGE_URL, wsApi } from "../../../../service/base_service"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    windowWidth: 0,
    scrollRefreshStatus: true,
    chatList: [

    ],
    intoChatView: "",//默认要滚动到的chatItem;
    scrollBottomHeight: COMMON_SCROLLBOTTOM,//scroll到底部的绝对距离，默认120.
    functionToolShow: false,//工具栏是否显示
    emojiToolShow: false,//表情工具栏是否显示
    isBottomToolShow: false,
    emojiStrs: [
      ["😀", "😃", "😄", "🤓", "😏", "😅", "😋", "🤪",
        "😝", "😛", "🤑", "😎", "🧐", "🥳", "🤗", "🤔",
        "😱", "🥺", "😤", "😧", "😓", "😭", "🤩", "🤕", "😴", "❎"],
      ["💩", "👻", "🎃", "😹", "🙀", "👏", "🙏", "🤝", "👍", "👊", "✊", "🤟", "👌",
        "🤙", "💪", "💔", "❎"
      ]
    ],
    textareaContent: "",//输入文字内容
    inputFocus: false,//输入框是否聚焦了
    inputHeight: 0,
    /* 音频参数 */
    __comps__: {
      audio: null
    },
    audioContext: null,//音频播放上下文
    audioSaveID: '',//保存上一次播放的音频ID
    audioPlayStatus: false,//音频是否处于播放状态
    /* 音频参数 */
    //TIM需要参数:
    chatUserId: '',//聊天对方id
    currentUserId: null,//自己的openId
    chatType: 0,//0:单聊，1:群聊
    conversationType: "C2C",//会话类型
    conversationID: "",//会话id
    messageList: [],//聊天列表
    nextReqMessageID: null,//拉取历史消息ID
    isCompleted: true,//是否完成消息拉取
    historyList: [],
    fromNick: "",//单聊对方的nick
    fromAvatar: "",//单聊对方的avatar //最开始的时候请给一个默认的昵称和头像
    myNick: "",
    myAvatar: "",//自己的头像
    //TIM需要参数:
    chatData: {},
    expertId: null,
    expertPhone: "",
    expertWeChat: "",
    isShowExpertInfo: false,//是否显示经纪人情况
    isBindMp: false,//自己是否绑定公众号
    houseName: "",//房源名
    houseNumber: "",//房源编号
    houseCover: "",
    housePrice: "",
    houseDesc: "",
    houseType: 1,
    saleType: 2,//商铺的租或者卖类型，1，2，3
    // imTODO 消息列表传参:
    msgParams: {
      page: 0,
      pageSize: 15,
      userId: "",
    },
    wxMpLink: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.wxMpLink) {
      this.setData({
        wxMpLink: app.globalData.wxMpLink
      })
    }
    this.setData({
      windowWidth: app.globalData.windowWidth,
      isBindMp: app.globalData.isBindMp || false
    })
    let audioContext = wx.createInnerAudioContext();//音频播放实例
    this.setData({
      chatData: app.globalData.chatData,
      conversationID: "C2C" + app.globalData.chatData.chatUserId,
      chatUserId: app.globalData.chatData.chatUserId,
      currentUserId: app.globalData.openId,
      myAvatar: app.globalData.avatar,
      myNick: app.globalData.nickName,
      fromNick: app.globalData.chatData.name,
      fromAvatar: app.globalData.chatData.avatar,
      expertId: app.globalData.chatData.expertId || null,
      expertPhone: app.globalData.chatData.expertPhone || "",
      expertWeChat: app.globalData.chatData.expertWeChat || "",
      audioContext: audioContext,
      // imTODO
      'msgParams.userId': app.globalData.chatData.chatUserId,
    })
    //当聊天id和当前页面人的id相同的话证明就是自己和自己聊天
    if (this.data.chatUserId == this.data.currentUserId) {
      wx.showToast({
        title: '自己不能和自己聊天',
        icon: 'none',
        duration: 3000,
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 0,
        })
      }, 3000)
    }

    wx.setNavigationBarTitle({
      title: this.data.fromNick
    })
    if (this.data.expertId && this.data.expertPhone) {
      this.setData({
        isShowExpertInfo: true
      })
    }
    this.setMessageRead();
    console.log("JJLog:聊天参数是====:" + JSON.stringify(this.data.chatData));
    if (this.data.chatData.houseName) {
      this.setData({
        houseName: this.data.chatData.houseName,
        houseNumber: this.data.chatData.houseNumber,
        houseCover: this.data.chatData.houseCover,
        housePrice: this.data.chatData.housePrice,
        houseDesc: this.data.chatData.houseDesc,
        houseType: this.data.chatData.houseType || 1
      })
      if (this.data.houseType == 4) {
        this.setData({
          saleType: this.data.chatData.saleType
        })
      }
      //发送自定义的楼盘消息:
      this.sendCustomHouseMsg();

    }
    let that = this;
    //监听这个最新收到的聊天信息:
    app.watch(that.watchBack);
    //第一次加载聊天消息列表:
    // this.getMsgList();
    // imTODO 加载新的聊天消息列表
    this.getNewMsgList();
    //设置消息滚动到最后一条消息:
    this.setScrollToBottom();
    //监听音频播放:
    audioContext.onPlay(() => {
      console.log("JJLog:语音播放中");
      this.setData({
        audioPlayStatus: true
      })
    })
    audioContext.onPause(() => {
      console.log("JJLog:语音暂停中");
      this.setData({
        audioPlayStatus: false
      })
    })
    audioContext.onStop(() => {
      console.log("JJLog:语音停止");
      this.setData({
        audioPlayStatus: false,
        audioSaveID: ""
      })

    })
    audioContext.onEnded(() => {
      console.log("JJLog:语音播放结束");
      this.setData({
        audioPlayStatus: false,
        audioSaveID: ""
      })
    })
  },
  // imTODO 
  onHide() {
    this.setMessageRead();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
  },
  //监听收到的最新聊天信息 -- 还得判断这条信息的from是不是当前聊天人才行哈
  watchBack: function (newChatMsg) {
    console.log('监听收到了最新聊天信息(聊天页面):' + JSON.stringify(newChatMsg));
    if (newChatMsg.send == this.data.chatData.chatUserId) {
      this.setData({
        historyList: [...this.data.historyList, newChatMsg]
      })
      this.setScrollToBottom();
    }

  },
  // imTODO 获取新的聊天列表:
  getNewMsgList() {
    wx.showLoading();
    queryIMMessageList(this.data.msgParams).then(res => {
      wx.hideLoading();
      console.log("JJLog:获取到的新消息列表====:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data && res.data.length < 1) {
          return;
        }
        // let nextReqMessageID = res.data[0].id;
        // imTODO
        let isCompleted = true;
        if (res.data.length > (this.data.msgParams.pageSize - 1)) {
          isCompleted = false;
        }
        this.setData({
          historyList: res.data,
          isCompleted: isCompleted
        })
        this.setScrollToBottom();
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '获取聊天失败',
        icon: "none"
      })
      console.error("JJLog:获取新消息列表失败===:", err);
    })
  },


  //消息已读上报:
  // setMessageRead() {
  //   let promise = app.globalData.tim.setMessageRead({ conversationID: this.data.conversationID });
  //   promise.then(imResponse => {
  //     console.log("JJLog:上报消息已读成功");
  //   }).catch(imError => {
  //     // 已读上报失败
  //     console.warn('JJLog:上报消息已读失败:', imError);
  //   });
  // },
  // imTODO 消息已读上报:
  setMessageRead() {
    setMessageIsRead({ userId: app.globalData.chatData.chatUserId }).then(res => {
      console.log("JJLog:设置消息已读成功");
      if (res.code == 200) {

      }
    }).catch(err => {
      console.error("JJLog:设置消息已读失败===", err);
    })
  },



  //表情栏按钮点击:
  emojiToolAction() {
    this.setData({
      emojiToolShow: !this.data.emojiToolShow,
      functionToolShow: false,
    })
    if (this.data.emojiToolShow) {
      this.setData({
        scrollBottomHeight: EMOJI_TOOLHEIGHT,
        isBottomToolShow: true
      })
    } else {
      this.setData({
        scrollBottomHeight: COMMON_SCROLLBOTTOM,
        isBottomToolShow: false
      })
    }
    this.setScrollToBottom();
  },
  //工具栏添加按钮点击:
  functionToolAction() {
    this.setData({
      functionToolShow: !this.data.functionToolShow,
      emojiToolShow: false
    })
    if (this.data.functionToolShow) {
      this.setData({
        scrollBottomHeight: FUNCTION_TOOLHEIGHT,
        isBottomToolShow: true
      })
    } else {
      this.setData({
        scrollBottomHeight: COMMON_SCROLLBOTTOM,
        isBottomToolShow: false
      })
    }
    this.setScrollToBottom();
  },

  //输入回调
  bindInputAction(e) {
    // console.log("JJLog:e=:" + JSON.stringify(e));
    this.setData({
      textareaContent: e.detail.value
    })
    this.dealInputBarHeight();


  },
  // 处理输入框高度方法:
  dealInputBarHeight() {
    let id = "#chatInputView";
    let query = wx.createSelectorQuery();//创建查询对象
    query.select(id).boundingClientRect();//获取view的边界及位置信息
    query.exec((res) => {
      if (res[0].height > 44) {
        // 这里暂时写死414，实际上应该是this.data.windowWidth
        this.setData({
          inputHeight: res[0].height * (750 / 414) + 20
        });
      } else {
        this.setData({
          inputHeight: 0
        })
      }
      console.log("JJLog:高度是:" + this.data.inputHeight);
    });
    this.setScrollToBottom();
  },
  //表情输入:
  emojiTextInput(e) {
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    let arr = e.currentTarget.dataset.arr;
    if (index == arr.length - 1) {
      let splitter = new GraphemeSplitter();
      let graphemes = splitter.splitGraphemes(this.data.textareaContent);//将含有表情的字符串分割成数组
      graphemes.pop();//删除数组中最后一个元素
      let str = graphemes.join('');//将数组还原成字符串

      this.setData({
        textareaContent: str
      })

    } else {
      this.setData({
        textareaContent: this.data.textareaContent + item
      })

    }
    this.dealInputBarHeight();


  },

  //发送文字消息:
  onConfirm() {
    console.log("JJLog:发送文字消息===");
    this.onsend();
  },
  sendEmojiAction() {
    this.onsend();
  },
  onsend() {
    let comment = this.data.textareaContent
    if (!comment) {
      wx.showToast({
        title: '消息不能为空',
        icon: "none"
      })
      return;
    }
    const parsedComment = {
      from: true,
      text: comment,
      id: `chatItem_${this.data.historyList.length}`
    }
    console.log("JJLog:点击onSend后调用的是什么:" + JSON.stringify(parsedComment));
    // imTODO 新的Im发送文字消息:
    this.newSendTextMessage(comment);
    // this.sendTextMessage(JSON.stringify(parsedComment));
    this.commonInputHeightDeal();
  },
  // imTODO 新的文字消息发送
  newSendTextMessage(comment) {
    let that = this;
    let sendMsgData = {
      send: app.globalData.openId,
      receive: this.data.chatData.chatUserId,
      info: {
        payload: {
          text: comment,
        }
      },
      msgType: "MSG_TEXT",
      appId: app.globalData.imAppId,
      time: new Date().getTime(),

    }
    app.globalData.socketTask.send({
      data: JSON.stringify(sendMsgData),
      success: (res) => {
        console.log("JJLog:新IM发送消息成功=====:" + JSON.stringify(res));
        that.sendImMsgConfig(comment, that.data.chatData.chatUserId, "text");
        that.setData({
          historyList: [...that.data.historyList, sendMsgData]
        })
        that.setScrollToBottom();
      },
      fail: (err => {
        this.connectSocketMethod(comment)
        wx.showToast({
          title: '发送失败，请重试',
          icon: "none"
        })
        console.error("JJLog:新IM发送消息失败:", err)

      })
    })
  },
  pushToOfficalPage() {
    //跳转webView
    app.globalData.webUrl = app.globalData.wxMpLink;
    wx.navigateTo({
      url: '/pages/webViewPage/webViewPage',
    })
  },
  connectSocketMethod(comment) {
    //1.建立socket连接:
    let that = this;
    app.globalData.socketTask = wx.connectSocket({
      url: wsApi,
      success: function () {
        console.log("========= webSocket客户端连接成功！=========");
        // that.newSendTextMessage(comment)
        app.globalData.socketOpen = true;
      },
      fail: (err => {
        console.error("JJLog:连接socket失败===:" + JSON.stringify(err));
        app.globalData.socketOpen = false;
      })
    })
  },


  //公共的发送消息后输入框处理方法:
  commonInputHeightDeal() {
    this.setData({
      textareaContent: '',
      emojiToolShow: false,
      functionToolShow: false,
      inputHeight: 0,
      scrollBottomHeight: COMMON_SCROLLBOTTOM,
    })

  },

  //图片消息========
  functionToolClick(e) {
    // console.log("JJLog:功能栏点击:" + JSON.stringify(event));
    this.commonInputHeightDeal();
    let type = e.currentTarget.dataset.type;
    if (type == 'photo') {
      //从相册选择:
      this.chooseImage(['album'])
    } else if (type == 'camera') {
      //相机拍照:
      this.chooseImage(['camera'])
    }
  },
  //选择照片:
  chooseImage(fromArr) {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: fromArr,
      success(res) {
        console.log("JJLog:选择图片成功:" + JSON.stringify(res));
        // 新的发送图片消息方法:
        that.newSendImgMessage(res);
        return;
        let message = app.globalData.tim.createImageMessage({
          to: that.data.chatData.chatUserId,
          conversationType: that.data.chatData.conversationType,
          payload: { file: res },
          onProgress: function (event) { console.log('file uploading:', event) }
        });
        // 3. 发送图片
        wx.showLoading({
          title: '图片发送中...',
        })
        let promise = app.globalData.tim.sendMessage(message);
        promise.then(function (imResponse) {
          console.log("JJLog:发送图片消息成功:=======");
          wx.hideLoading();
          that.sendImMsgConfig("图片消息", that.data.chatData.chatUserId, "image");
          that.setData({
            historyList: [...that.data.historyList, imResponse.data.message]
          })
          that.setScrollToBottom();
          // that.msgIsSend();
        }).catch(function (imError) {
          wx.hideLoading();
          wx.showToast({
            title: '图片发送失败',
            icon: "none"
          })
          console.warn('JJLog发送图片消息失败===:', imError);
        });
      }
    })
  },
  // imTODO 新的发送图片消息
  newSendImgMessage(res) {
    wx.showLoading({
      title: '图片发送中...',
    })
    let that = this;
    let url = "https://up-z2.qiniup.com"
    let filePath = res.tempFilePaths[0]
    let keyPref = "/tempIm"
    let expandName = filePath.substring(filePath.length - 10, filePath.length)

    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: 'file',
      formData: {
        'token': wx.getStorageSync('qiniu_token'),
        'key': keyPref + "/" + new Date().getTime() + expandName,
      },
      header: {
        "Content-Type": "multipart/form-data"
      },
      success: function (res) {
        wx.hideLoading();
        let resultData = JSON.parse(res.data);
        resultData.complateUrl = NEWIMAGE_URL + resultData.key
        let sendMsgData = {
          send: app.globalData.openId,
          receive: that.data.chatData.chatUserId,
          info: {
            payload: {
              text: "",
              imageUrl: resultData.complateUrl
            }
          },
          msgType: "MSG_IMAGE",
          appId: app.globalData.imAppId,
          time: new Date().getTime(),
        }
        app.globalData.socketTask.send({
          data: JSON.stringify(sendMsgData),
          success: (res) => {
            console.log("JJLog:新IM发送图片消息成功=====")
            that.sendImMsgConfig("图片消息", that.data.chatData.chatUserId, "image");
            that.setData({
              historyList: [...that.data.historyList, sendMsgData]
            })
            that.setScrollToBottom();
          },
          fail: (err => {
            wx.showToast({
              title: '消息发送失败',
              icon: "none"
            })
            console.error("JJLog:新IM发送图片消息失败:", err)
          })
        })
      },
      fail: function (err) {
        wx.hideLoading();
        console.error("JJLog:图片上传失败:", err)
        wx.showToast({
          title: '消息发送失败',
          icon: "none"
        })
      }
    })
  },

  //图片预览
  imgMsgClick(e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: [url]
    })
  },



  //图片消息=========


  //设置scroll滚动到最后一个元素
  setScrollToBottom() {
    // console.log("JJLog:=======")
    this.setData({
      intoChatView: 'chatItem-' + (this.data.historyList.length - 1)
    })
  },







  //音频按钮点击:
  toggleRecordModal() {
    this.data.__comps__.audio.toggleRecordModal();
    this.commonInputHeightDeal();
  },
  //音频消息发送成功回调:
  saveAudioMsg(data) {
    console.log("JJLog:发送音频消息成功的回调:");
    let audioMsg = data.detail.msg;
    this.setData({
      historyList: [...this.data.historyList, audioMsg]
    })
    this.setScrollToBottom();
  },
  //语音播放点击:
  audioMsgClick(e) {
    //  console.log("JJLog:音频消息点击:" + JSON.stringify(e));
    let audioPath = e.currentTarget.dataset.audiopath;
    let audioID = e.currentTarget.dataset.audioid;
    let currentAudioID = this.data.audioSaveID;
    this.data.audioContext.src = audioPath;
    if (currentAudioID == audioID) {
      //播放同一条语音，暂停其播放:
      this.data.audioContext.pause();
      this.setData({
        audioSaveID: ''
      })
    } else {
      //不是同一条语音直接播放:
      this.data.audioContext.play();
      this.setData({
        audioSaveID: audioID
      })
    }
  },


  //键盘监听
  keyBoardHeightChange(e) {

  },

  onReady: function () {
    this.data.__comps__.audio = this.selectComponent("#chat-audio")
  },

  // scroll下拉刷新:
  refreshDownData() {
    console.log("JJLog:下拉刷新=====");
    if (this.data.isCompleted) {
      //已经拉完所有消息了
      this.setData({
        scrollRefreshStatus: false
      })
      wx.showToast({
        title: '没有更多消息啦',
        icon: "none"
      })
    } else {
      this.setData({
        scrollRefreshStatus: true
      })
      this.getMoreMsgList();
    }
  },

  //获取聊天列表:
  getMoreMsgList() {
    this.getMoreNewIMList();
    return;
    wx.showLoading();
    let hList = this.data.historyList;
    let that = this;
    let promise = app.globalData.tim.getMessageList({ conversationID: this.data.conversationID, nextReqMessageID: this.data.nextReqMessageID, count: 15 });
    promise.then(function (imResponse) {
      console.log("JJLog:拉取更多聊天列表拉取数据:" + JSON.stringify(imResponse));
      const messageList = imResponse.data.messageList; // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      wx.hideLoading();
      let resultList = imResponse.data.messageList.concat(hList);
      that.setData({
        scrollRefreshStatus: false,
        historyList: resultList,
        nextReqMessageID: imResponse.data.nextReqMessageID,
        isCompleted: imResponse.data.isCompleted
      })
    }).catch(function (imError) {
      //加载消息失败
      wx.hideLoading();
      that.setData({
        scrollRefreshStatus: false,
      })
      wx.showToast({
        title: '消息加载失败',
        icon: "none"
      })
    });
  },
  // imTODO
  getMoreNewIMList() {
    wx.showLoading();
    let hList = this.data.historyList;
    let that = this;
    this.setData({
      'msgParams.page': this.data.msgParams.page + 1
    })
    queryIMMessageList(this.data.msgParams).then(res => {
      wx.hideLoading();
      console.log("JJLog:获取到的新消息列表====:" + JSON.stringify(res));
      if (res.code == 200) {

        if (res.data && res.data.length < 1) {
          return;
        }
        const messageList = res.data; // 消息列表。
        // let nextReqMessageID = res.data[0].id;
        let isCompleted = true;
        if (res.data.length > (this.data.msgParams.length - 1)) {
          isCompleted = false;
        }
        let resultList = messageList.concat(hList);
        this.setData({
          scrollRefreshStatus: false,
          historyList: resultList,
          // "msgParams.msgId": nextReqMessageID,
          isCompleted: isCompleted
        })

      }
    }).catch(err => {
      wx.hideLoading();
      that.setData({
        scrollRefreshStatus: false,
        'msgParams.page': this.data.msgParams.page - 1
      })
      wx.showToast({
        title: '加载历史消息失败',
        icon: "none"
      })
      console.error("JJLog:加载历史消息列表失败===:", err);
    })
  },


  //统一的下消息配置发送:
  sendImMsgConfig(content, toOpenId, type) {
    let textContent = ""
    console.log("JJog:content:" + content)
    if (type == "text") {
      // imTODO
      textContent = content;
    } else {
      textContent = content;
    }
    let obj = {
      content: textContent,
      toOpenId: toOpenId,
    }
    console.log("JJLog:稍等哈的数据:" + JSON.stringify(obj));
    sendImMsgConfig(obj).then(res => {

    }).catch(err => {
      console.error("JJLog:sendImMsgConfig", err);
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setMessageRead();
  },


  //跳转到公众号页面:
  pushToOfficalAction() {
    wx.navigateTo({
      url: '/firstPackage/pages/officialAccounts/officialAccounts',
    })
  },
  //跳转到置业顾问主页
  pushToExpertDetail() {
    wx.navigateTo({
      url: '/firstPackage/pages/expertModule/newExpertDetail/newExpertDetail?id=' + this.data.expertId,
    })
  },

  //复制微信号
  copyWxChatAction() {
    if (!this.data.expertWeChat) {
      wx.showToast({
        title: '暂无专家微信号',
        icon: "none"
      })
      return;
    }
    let text = this.data.expertWeChat
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制微信号成功'
            })
          },
          fail: function (err) {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })
  },
  //给专家打电话
  playExpertPhoneAction() {
    wx.makePhoneCall({
      phoneNumber: this.data.expertPhone,
      fail: err => {

      }
    })
  },



  //发送自定义的楼盘消息
  sendCustomHouseMsg() {
    let that = this;
    let msgData = {
      cover: this.data.houseCover,
      houseName: this.data.houseName,
      houseDesc: this.data.houseDesc,
      price: this.data.housePrice,
      houseNumber: this.data.houseNumber,
      houseType: this.data.houseType,
      saleType: this.data.saleType,
    }

    let sendMsgData = {
      send: app.globalData.openId,
      receive: this.data.chatData.chatUserId,
      info: {
        payload: {
          text: "",
          data: msgData,
          type: 'houseMsg'
        }
      },
      msgType: "MSG_CUSTOM",
      appId: app.globalData.imAppId,
      time: new Date().getTime(),
    }
    app.globalData.socketTask.send({
      data: JSON.stringify(sendMsgData),
      success: (res) => {
        console.log("JJLog:新IM房源发送消息成功=====:" + JSON.stringify(res));
        that.sendImMsgConfig('房源咨询消息', that.data.chatData.chatUserId, "house");
        that.setData({
          historyList: [...that.data.historyList, sendMsgData]
        })
        that.setScrollToBottom();
      },
      fail: (err => {
        console.error("JJLog:新IM发送消息失败:", err)
      })
    })

    return;
    let jsonData = JSON.stringify(msgData);
    let message = app.globalData.tim.createCustomMessage({
      to: this.data.chatData.chatUserId,
      conversationType: this.data.chatData.conversationType,
      payload: {
        data: jsonData,
        description: "customHouse",
        extension: "",
      }
    });
    // 2. 发送消息
    let promise = app.globalData.tim.sendMessage(message);
    promise.then(function (imResponse) {
      // 发送成功
      console.log("JJLog:发送自定义房源消息:" + JSON.stringify(imResponse));
      that.sendImMsgConfig("房源消息", that.data.chatData.chatUserId, "custom");
      that.setData({
        historyList: [...that.data.historyList, imResponse.data.message]
      })
      that.setScrollToBottom();
      // that.msgIsSend();
    }).catch(function (imError) {
      wx.showToast({
        title: '自定义房源消息发送失败',
        icon: "none"
      })
      // 发送失败
      console.error('JJLog发送自定义房源消息失败:', imError);
    });
  },

  //跳转到房源详情:
  pushToHouseDetail(e) {
    let item = e.currentTarget.dataset.item;

    let houseNumber = item.houseNumber;
    let houseType = item.houseType;
    if (houseType == 1) {
      //新房
      wx.navigateTo({
        url: '/newHousePackage/pages/newHouseDetail/newHouseDetail?houseNumber=' + houseNumber,
      })
    } else if (houseType == 2) {
      //二手
      wx.navigateTo({
        url: '/secondHousePackage/pages/secondHouseDetail/secondHouseDetail?houseNumber=' + houseNumber,
      })
    } else if (houseType == 4) {
      wx.navigateTo({
        url: '/secondHousePackage/pages/shopModule/shopHouseDetail/shopHouseDetail?shopNumber=' + houseNumber,
      })
    }

  },

})